#!/usr/bin/env python
from __future__ import print_function
import numpy as np
from maputility2.skyutils import fastOpen

def showMinMax(infile, extidx=None, ebin=False):
    m = fastOpen(infile, verbose=False, extidx=extidx, container='pixmap')

    print(infile+':')
    if ebin:
        mapshape = tuple(range(1, m.mapdata.ndim))
        min_val = m.mapdata.min(mapshape)
        max_val = m.mapdata.max(mapshape)
        mean_val = m.mapdata.mean(mapshape)
        std_val = m.mapdata.std(mapshape)
        sum_val = m.mapdata.sum(mapshape)
        for ib, mn, mx, me, st, su in zip(range(m.nlayers), min_val, max_val, mean_val, std_val, sum_val):
            print('[%02d]: %.7g(min), %.7g(max), %.7g(mean), %.5g(std), %.10g(sum)'
                  % (ib, mn, mx, me, st, su))
    else:
        min_val = m.mapdata.min()
        max_val = m.mapdata.max()
        mean_val = m.mapdata.mean()
        std_val = m.mapdata.std()
        sum_val = m.mapdata.sum()
        print('%.7g(min), %.7g(max), %.7g(mean), %.5g(std), %.10g(sum)'
              % (min_val, max_val, mean_val, std_val, sum_val))

if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser(description='Find minimum and maximum of the input file!')
    parser.add_argument("infiles", nargs='+', help='input file(s)')
    parser.add_argument("-e", action='store_true', default=False, help='show min and max in each energy bin')
    parser.add_argument("-t", type=str, default=None, help='the extension name')
    parser.add_argument("-i", type=int, default=None, help='the index of the extension')
    args = parser.parse_args()

    extidx = None
    if args.t is not None:
        extidx = args.t
    elif args.i is not None:
        extidx = args.i

    for infile in args.infiles:
        showMinMax(infile, extidx, args.e)
